<template>
  <div>
    <el-button type="primary" icon="el-icon-plus" @click="showDialog">添加</el-button>

    <!-- 表格 -->
    <el-table style="width: 100%" border :data="list">
      <el-table-column prop="date" label="序号" width="80px" align="center" type="index"> </el-table-column>
      <el-table-column prop="title" label="品牌名称" width="width"> </el-table-column>
      <el-table-column prop="imageUrl" label="品牌LOGO" width="width">
        <template slot-scope="{ row, $index }"><img :src="row.imageUrl" alt="" style="width: 100px; height: 100px" /></template>
      </el-table-column>
      <el-table-column prop="date" label="操作" width="width">
        <template slot-scope="{ row, $index }">
          <el-button type="warning" icon="el-icon-edit" size="mini" @click="updateTradeMark(row)">修改</el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteTradeMark(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <!-- @size-change="handleSizeChange"
      @current-change="handleCurrentChange" -->
    <el-pagination
      style="text-align: center; margin-top: 20px"
      :current-page="page"
      :page-size="limit"
      :page-sizes="[3, 5, 10]"
      layout=" prev, pager, next,->,sizes,total"
      :total="total"
      :popper-count="7"
      @current-change="getPageList"
      @size-change="handleSizeChange"
    >
    </el-pagination>
    <!-- //对话框 -->
    <el-dialog :title="tmForm.id ? '修改品牌' : '添加品牌'" :visible.sync="dialogFormVisible">
      <!-- form表单 -->
      <el-form style="width: 60%" :model="tmForm" :rules="rules" ref="ruleForm">
        <el-form-item label="品牌名称" label-width="100px" prop="title">
          <el-input autocomplete="off" v-model="tmForm.title"></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" label-width="100px" prop="imageUrl">
          <!-- 上传插件 -->

          <el-upload
            class="avatar-uploader"
            action="/dev-api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <!-- :on-success="handleAvatarSuccess"  上传成功执行一次-->
            <!-- :before-upload="beforeAvatarUpload"  上传成功之前执行一次-->
            <!-- action 图片上传地址 -->
            <img v-if="tmForm.imageUrl" :src="tmForm.imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrUpdateTradeMark">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'tradeMark',
  data() {
    //  自定义验证规则
    var validateTitle = (rule, value, callback) => {
      if (value.length < 2 || value.length > 10) {
        callback(new Error('品牌名称2-10位'))
      } else {
        callback()
      }
    }
    return {
      page: 1,
      limit: 3,
      total: 0, //总数据条数
      list: [], //列表展示的数据
      dialogFormVisible: false, //控制对话框显示

      tmForm: {
        // logoUrl: '',
        imageUrl: '',
        title: '',
      }, //收集品牌信息 属性名字要看文档上的
      rules: {
        title: [
          { required: true, message: '请输入品牌名称', trigger: 'blur' },
          // { min: 2, max: 10, message: '长度在 3 到 5 个字符', trigger: 'change' },
          { validator: validateTitle, trigger: 'blur' }, //自定义验证规则
        ],
        imageUrl: [{ required: true, message: '请选择品牌图片' }],
      },
    }
  },
  mounted() {
    //获取列表数据的方法
    this.getPageList()
  },
  methods: {
    async getPageList(pager = 1) {
      this.page = pager
      //结构数据
      const { page, limit } = this
      //获取品牌列表的接口
      let result = await this.$API.trademark.reqTradeMarkList(page, limit)
      if (result.code === 200) {
        this.total = result.data.total
        this.list = result.data.records
        console.log(result)
      }
    },
    // 优化到上边函数内
    // handleCurrentChange(pager) {
    //   this.page = pager;
    //   this.getPageList();
    // },

    //当分页器某一页需要展示数据天数变化的时候触发
    handleSizeChange(limit) {
      this.limit = limit
      this.getPageList()
    },
    //点击添加按钮 显示对话框
    showDialog() {
      this.dialogFormVisible = true
      //清除对话框数据
      this.tmForm = { imageUrl: '', title: '' }
    },
    //修改品牌
    updateTradeMark(row) {
      //row 选中品牌的信息
      console.log(row)
      this.dialogFormVisible = true
      this.tmForm = { ...row }
    },
    // 图片上传成功
    handleAvatarSuccess(res, file) {
      // res是图片上传成功后返回的前端数据
      //file是图片上传成功后返回前端d的数据
      // console.log(res);
      // console.log(file);
      this.tmForm.imageUrl = res.data //把数据地址给服务器
    },
    // 图片上传成功之前
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    //添加按钮（添加或修改品牌）
    addOrUpdateTradeMark() {
      // 当全部验证字段都通过再去书写业务逻辑
      this.$refs.ruleForm.validate(async (success) => {
        if (success) {
          this.dialogFormVisible = false
          let result = await this.$API.trademark.reqAddOrUpdateTradeMark(this.tmForm)
          if (result.code == 200) {
            this.$message(this.tmForm.id ? '修改品牌成功' : '添加品牌成功')
            this.getPageList()
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    //删除品牌
    deleteTradeMark(row) {
      // console.log(row)
      //弹框
      this.$confirm(`删除${row.title}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          let result = await this.$API.repDeleteTradeMark(row.id)
          if (result.code == 200) {
            this.$message({
              //点击确定触发
              type: 'success',
              message: '删除成功!',
            })
            this.getPageList(this.list.length > 1 ? this.page : this.page - 1)
          }
        })
        .catch(() => {
          //点击取消的时候触发
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
  },
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
